package centerberg.game;

import centerberg.engine.Engine;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Stack;

/**
 * Simple stack-based menu system.
 * 
 * @author Andreas Svanberg
 */
public class MenuSystem extends KeyAdapter
{
    private static Stack<Menu> menus = new Stack<Menu>();
    private static Menu activeMenu;
    
    /**
     * Shows the given menu.
     */
    public static void showMenu(Menu menu)
    {
        Engine.getInstance().pause();
        menus.push(menu);
        update();
    }
    
    /**
     * Hides all menus and clears the stack of open menus.
     */
    public static void hideMenu()
    {
        menus.clear();
        activeMenu = null;
    }
    
    /**
     * Updates the visible menu.
     */
    private static void update()
    {
        activeMenu = menus.peek();
        activeMenu.show();
    }
    
    /**
     * Moves back (up) one step in the menu system.
     * If this was the last menu, the game engine is resumed.
     */
    public static void goBack()
    {
        menus.pop();
        if (menus.isEmpty())
            Engine.getInstance().resume();
        else
            update();
    }
    
    /**
     * Listens for key events to navigate the menus.
     * 
     * @param event the key event
     */
    @Override
    public void keyReleased(KeyEvent event)
    {
        switch (event.getKeyCode())
        {
            case KeyEvent.VK_ESCAPE:
                goBack();
                break;
            case KeyEvent.VK_DOWN:
                if (activeMenu != null)
                    activeMenu.next();
                break;
            case KeyEvent.VK_UP:
                if (activeMenu != null)
                    activeMenu.previous();
                break;
            case KeyEvent.VK_ENTER:
                if (activeMenu != null)
                    activeMenu.select();
                break;
        }
    }
    
    /**
     * When class is loaded add as keylistener.
     */
    static
    {
        Engine.getInstance().addKeyListener(new MenuSystem());
    }
}